package sg4c.protocol;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

public class TextOutputProtocol implements DataOutputProtocol {
    private final OutputStream os;
    private final BufferedWriter writer;

    public TextOutputProtocol(OutputStream os) {
        this.os = os;
        this.writer = new BufferedWriter(new OutputStreamWriter(os));
    }

    public void writeInt(int val) throws IOException {
        String out = Integer.toHexString(val);
        writer.write(out);
        writer.newLine();
        writer.flush();
    }


    public void writeFloat(float val) throws IOException {
        String out = Float.toHexString(val);
        writer.write(out);
        writer.newLine();
        writer.flush();
    }

    public void writeDouble(double val) throws IOException {
        String out = Double.toHexString(val);
        writer.write(out);
        writer.newLine();
        writer.flush();
    }

    /**
     *
     * @param val Should be using ASCII charset.
     * @return
     */
    public void writeString(String val) throws IOException {
        writeInt(val.getBytes().length);
        writer.write(val);
        writer.newLine();
        writer.flush();
    }

    public void flush() throws IOException {
        writer.flush();
    }
}
